﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using IOA.MES.Client.Settings;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using System.Reflection;
using EasyModbus;

namespace IOA.MES.Client.FinalInspection
{
    /// <summary>
    /// FinalInspectionIndex.xaml 的交互逻辑
    /// </summary>
    public partial class FinalInspectionIndex : Window
    {
        private WinScan winScan;
        private WinELImage winElImage;
        private FinalTip finalTip;
        private string imageUrl = string.Empty;

        public FinalInspectionIndex()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            lblTrueName.Content = BaseEnv.UserInfo.TrueName;

            InitDuties();
            InitMachines();
            InitBadReasons();
            InitSelections();
            finalTip = new FinalTip();
            finalTip.Show();

            new TaskFactory().StartNew(() =>
            {
                Thread.Sleep(100);
                Dispatcher.Invoke(new Action(() =>
                {
                    winScan = new WinScan(SetImage);
                    winScan.Closed += WinScan_Closed;
                    winScan.ShowDialog();
                }));
            });
        }

        public void InitDuties()
        {
            var duties = BaseEnv.InvokeApi<QueryDutiesResponse>("/api/Auth/QueryDuties", new { }).Data.Duties;

            cbDuties.ItemsSource = duties;
            cbDuties.DisplayMemberPath = "DutyName";
            cbDuties.SelectedValuePath = "DutyId";

            if (duties.Any())
            {
                cbDuties.SelectedIndex = 0;
            }
        }

        public void InitMachines()
        {
            var machines = BaseEnv.InvokeApi<QueryMachinesResponse>("/api/Machine/QueryMachines", new { MachineType = (int)MachineType.FinalInspection }).Data.Machines;
            cbMachines.ItemsSource = machines;
            cbMachines.DisplayMemberPath = "MachineName";
            cbMachines.SelectedValuePath = "MachineId";

            if (machines.Any(_ => _.MachineId == BaseEnv.MachineId))
            {
                cbMachines.SelectedIndex = machines.FindIndex(_ => _.MachineId == BaseEnv.MachineId);
            }
            else
            {
                CommonMessage.Alert(this, "请先在系统设置中重新选择设备\r\nPlease reselect the device in the system settings now"); ;
                new SettingsIndex().ShowDialog();
            }
        }

        public void InitBadReasons()
        {
            var reasons = BaseEnv.InvokeApi<QueryBadReasonsResponse>("/api/NQC/QueryBadReasons", new { ReasonType = 2 }).Data.BadReasons;

            foreach (var item in reasons)
            {
                var checkBox = new CheckBox();
                checkBox.Content = $"{item.ReasonCode}-{item.ReasonCN}";
                checkBox.Margin = new Thickness(10);
                checkBox.FontSize = 15;

                wpBadReasons.Children.Add(checkBox);
            }
        }

        public void InitSelections()
        {
            var selections = BaseEnv.InvokeApi<GetFinalInspectSelectionsResponse>("/api/NQC/GetFinalInspectSelections", new { }).Data;
            if (selections.QLevels.Count < 2)
            {
                CommonMessage.Alert(this, "系统需要至少配置2个以上判定等级，请联系工艺人员\r\nThe system needs to be configured with at least two or more judgment levels, please contact the technical staff");
                Environment.Exit(0);
            }
            selections.QLevels.Insert(0, "");
            cbLevels.ItemsSource = selections.QLevels;
            cbLevels.SelectedIndex = 0;

            cbTypes.ItemsSource = selections.ComponentTypes;
            cbTypes.SelectedIndex = 0;

            cbFeature.ItemsSource = selections.CellFeatures;
            cbFeature.SelectedIndex = 0;
        }

        private void WinScan_Closed(object sender, EventArgs e)
        {
            if (((WinScan)sender).DialogResult == true)
            {
                if (winScan.InspectData != null)
                {
                    lblBarCode.Content = winScan.InspectData?.ComponentData?.IvData?.BarCode ?? string.Empty;
                    lblPmax.Content = winScan.InspectData?.ComponentData?.IvData?.Pmax;
                    lblCurrentLevel.Content = winScan.InspectData?.ComponentData?.IvData?.IVCurrentLevel;
                    lblWorkOrderNo.Content = winScan.InspectData?.ComponentData?.WokrOrderNo ?? string.Empty;
                    lblIm.Content = winScan.InspectData?.ComponentData?.IvData?.Im;
                    lblVm.Content = winScan.InspectData?.ComponentData?.IvData?.Vm;
                    lblEnvTemp.Content = winScan.InspectData?.ComponentData?.IvData?.EnvTemp;
                    lblPower.Content = winScan.InspectData?.ComponentData?.IvData?.IVPowerLevel;
                    lblVoc.Content = winScan.InspectData?.ComponentData?.IvData?.Voc;
                    LblIsc.Content = winScan.InspectData?.ComponentData?.IvData?.Isc;
                    lblFF.Content = winScan.InspectData?.ComponentData?.IvData?.FF;
                    lblColor.Content = winScan.InspectData?.ComponentData?.ComponentColor ?? string.Empty;
                    lblEffectiveness.Content = "";
                    lblSchemaName.Content = winScan.InspectData?.ComponentData?.SchemaName ?? string.Empty;
                    lblVerifyCode.Content = winScan.InspectData?.VerifyCode ?? string.Empty;
                }
                new TaskFactory().StartNew(() =>
                {
                    Thread.Sleep(100);
                    Dispatcher.Invoke(new Action(() =>
                    {
                        winElImage = new WinELImage(GetImage);
                        winElImage.Closing += WinElImage_Closed;
                        winElImage.Closed += WinElImage_Closed;
                        winElImage.ShowDialog();
                    }));
                });
            }
        }

        public void SetImage(string image)
        {
            this.imageUrl = image;
            Dispatcher.Invoke(new Action(() =>
            {
                if (winElImage != null && PresentationSource.FromVisual(winElImage) != null)
                {
                    winElImage.SetImage(image);
                }
            }), System.Windows.Threading.DispatcherPriority.Background);
        }
        public string GetImage()
        {
            return imageUrl;
        }

        private void WinElImage_Closed(object sender, EventArgs e)
        {
            btnStart.Focus();
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            InitForms();
        }

        private void btnViaSite_Click(object sender, RoutedEventArgs e)
        {
            ViaSite();
        }

        private void cbLevels_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbLevels.SelectedIndex > 0)
            {
                ViaSite();
            }
        }
        private void ViaSite(bool isLock = false)
        {
            if (cbLevels.SelectedIndex == 0 && !isLock)
            {
                CommonMessage.Alert(this, "请选择判定等级");
                return;
            }
            var badReasons = new List<string>();
            foreach (var item in wpBadReasons.Children)
            {
                if (item is CheckBox && ((CheckBox)item).IsChecked == true)
                {
                    badReasons.Add(Convert.ToString(((CheckBox)item).Content).Trim().Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0]);
                }
            }
            var request = new
            {
                SiteType = SiteType.FinalInspection,
                MachineId = Convert.ToInt32(cbMachines.SelectedValue),
                DutyId = Convert.ToInt32(cbDuties.SelectedValue),
                Code = lblBarCode.Content,
                QLevel = isLock ? string.Empty : Convert.ToString(cbLevels.SelectedValue),
                IsLock = isLock,
                BadReasons = badReasons,
                ComponentType = isLock ? string.Empty : Convert.ToString(cbTypes.SelectedValue),
                CellFeature = isLock ? string.Empty : Convert.ToString(cbFeature.SelectedValue),
                VerifyCode = lblVerifyCode.Content,
                Images = new List<string>()
            };
            var response = BaseEnv.InvokeApi<ViaSiteResponse>("/api/Machine/ViaSite", request);
            if (response.ErrCode != 200)
            {
                mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                mediaElResult.Play();
                CommonMessage.Alert(this, response.ErrMsg);
                InitForms(false);
                return;
            }
            CommonMessage.Log(LogLevel.Info, $"过站成功：{Convert.ToString(lblBarCode.Content)?.Trim()}");
            mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Success.wav");
            mediaElResult.Play();

            if (response.Data.DutyId != Convert.ToInt32(cbDuties.SelectedValue))
            {
                cbDuties.SelectedValue = response.Data.DutyId;
            }

            SetTipData(new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("条码", request.Code.ToString()),
                new KeyValuePair<string, string>("等级", request.QLevel),
                new KeyValuePair<string, string>("是否锁定", request.IsLock ? "锁定" : "否"),
            });
            InitForms();
        }

        private void SetTipData(List<KeyValuePair<string, string>> data)
        {
            try
            {
                finalTip.SetData(data);
            }
            catch (Exception ex)
            {
                CommonMessage.Log(LogLevel.Warn, $"设置弹窗数据异常：{ex.Message}", ex);
            }
        }

        private void InitForms(bool autoNext = true)
        {
            new TaskFactory().StartNew(() =>
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    cbLevels.SelectedIndex = 0;
                    this.Focus();
                    keyEnter = string.Empty;
                    foreach (var item in wpBadReasons.Children)
                    {
                        if (item is CheckBox)
                        {
                            ((CheckBox)item).IsChecked = false;
                        }
                    }
                    if (autoNext)
                    {
                        winScan = new WinScan(SetImage);
                        winScan.Closed += WinScan_Closed;
                        winScan.ShowDialog();
                    }
                }));
            });
        }

        private string keyEnter = string.Empty;
        private DateTime keyTime = DateTime.MinValue;
        private void Window_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (e.Text.Trim().Length > 1)
            {
                mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\ChangeEnglish.mp3");
                mediaElResult.Play();
                return;
            }
            if ((DateTime.Now - keyTime).TotalMilliseconds > 100)
            {
                keyEnter = e.Text.Trim();
            }
            else
            {
                keyEnter = keyEnter + e.Text.Trim();
            }
            keyTime = DateTime.Now;

            if (keyEnter.Trim().Length < 2)
            {
                return;
            }

            CommonMessage.Log(LogLevel.Info, $"keyEnter:{keyEnter}");
            var level = keyEnter.Replace("_", "").Replace("-", "").ToUpper().Trim();
            if (level.StartsWith("SD", StringComparison.CurrentCultureIgnoreCase))
            {
                ViaSite(true);
            }
            else
            {
                var levels = cbLevels.ItemsSource as List<string>;
                var index = levels.Select(_ => _.ToUpper().Trim()).ToList().IndexOf(level);
                if (index > -1)
                {
                    cbLevels.SelectedIndex = index;
                }
            }
        }

        private void Menu_Click(object sender, RoutedEventArgs e)
        {
            switch (((MenuItem)sender).Name)
            {
                case "btnSettings":
                    new SettingsIndex().ShowDialog();
                    break;
                case "btnMissingRecords":
                    new MissingSiteRecord(Convert.ToInt32(cbMachines.SelectedValue)).Show();
                    break;
                case "btnLogout":
                    new LoginWindow(false).Show();
                    this.Hide();
                    break;
                case "btnAbout":
                    MessageBox.Show($"VinaSolarMes Product Version:{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion}");
                    break;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (finalTip != null && PresentationSource.FromVisual(finalTip) != null)
            {
                finalTip.Close();
            }
            Environment.Exit(0);
        }

        private void Window_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            keyEnter = string.Empty;
        }

        private void btnLock_Click(object sender, RoutedEventArgs e)
        {
            ViaSite(true);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
        }
    }
}
